<template>
  <div>
    <VForm
      ref="refForm"
      v-model="isFormValid"
      @submit.prevent="saveItem"
    >
      <VExpansionPanels
        v-model="openedPanels"
        disabled
        multiple
      >
        <VExpansionPanel :key="0">
          <VExpansionPanelTitle>基础配置</VExpansionPanelTitle>
          <VExpansionPanelText>
            <VRow class="lf-config-row">
              <VCol cols="6">
                <VSelect
                  v-model="jobGroup"
                  :rules="[requiredValidator]"
                  label="任务执行器"
                  :items="jobGroupOption"
                  class="lf-config-item"
                  hint="任务执行器（必选项）"
                  clearable
                  color="success"
                  item-title="title"
                  item-value="id"
                />
              </VCol>
              <VCol cols="6">
                <VTextField
                  v-model="jobDesc"
                  :rules="[requiredValidator]"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="任务名称（必填项）"
                  label="任务名称"
                />
              </VCol>
              <VCol cols="6">
                <VTextField
                  v-model="author"
                  :rules="[requiredValidator]"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="负责人（必填项）"
                  label="负责人"
                />
              </VCol>
              <VCol cols="6">
                <VTextField
                  v-model="alarmEmail"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="报警邮件"
                  label="报警邮件"
                />
              </VCol>
            </VRow> 
          </VExpansionPanelText>
        </VExpansionPanel>

        <VExpansionPanel :key="1">
          <VExpansionPanelTitle>调度配置</VExpansionPanelTitle>
          <VExpansionPanelText>
            <VRow class="lf-config-row">
              <VCol cols="6">
                <VAutocomplete
                  v-model="scheduleType"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="调度类型（必选项）"
                  label="调度类型"
                  :rules="[requiredValidator]"
                  :items="option.scheduleType.list"
                  item-title="title"
                  item-value="value"
                />
              </VCol>
              <VCol
                v-if="scheduleConfShow"
                cols="6"
              >
                <VTextField
                  v-model="scheduleConf"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  :hint="scheduleConfHint"
                  :label="scheduleConfLabel"
                />

                <VCron
                  v-if="scheduleType == 'CRON'"
                  v-model:value="state.cron"
                  i18n="cn"
                  max-height="350px"
                  style="flex: 0.4;"
                  @change="changeCron"
                />
              </VCol>
            </VRow> 
          </VExpansionPanelText>
        </VExpansionPanel>

        <VExpansionPanel :key="2">
          <VExpansionPanelTitle>任务配置</VExpansionPanelTitle>
          <VExpansionPanelText>
            <VRow class="lf-config-row">
              <VCol cols="6">
                <VAutocomplete
                  v-model="glueType"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="运行模式（必选项）"
                  label="运行模式"
                  :rules="[requiredValidator]"
                  :items="option.glueType.list"
                  item-title="title"
                  item-value="value"
                />
              </VCol>
              <VCol
                v-if="executorHandlerShow"
                cols="6"
              >
                <VTextField
                  v-model="executorHandler"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="JobHandler（必选项）"
                  label="JobHandler"
                />
              </VCol>
              <VCol
                v-if="chainIdShow"
                cols="6"
              >
                <VAutocomplete
                  v-model="chainId"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="LiteFlow链路（必选项）"
                  label="LiteFlow链路"
                  :items="chainOptions"
                  item-title="chainName"
                  item-value="chainId"
                />
              </VCol>
              <VCol cols="12">
                <VTextarea
                  v-model="executorParam"
                  class="lf-config-item"
                  label="任务参数"
                  clearable
                  counter
                  maxlength="255"
                  hint="任务参数"
                />
              </VCol>
            </VRow> 
          </VExpansionPanelText>
        </VExpansionPanel>

        <VExpansionPanel :key="3">
          <VExpansionPanelTitle>高级配置</VExpansionPanelTitle>
          <VExpansionPanelText>
            <VRow class="lf-config-row">
              <VCol cols="6">
                <VAutocomplete
                  v-model="executorRouteStrategy"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="路由策略（必选项）"
                  label="路由策略"
                  :rules="[requiredValidator]"
                  :items="option.executorRouteStrategy.list"
                  item-title="title"
                  item-value="value"
                />
              </VCol>
              <VCol cols="6">
                <VTextField
                  v-model="childJobId"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="子任务ID，如果存在多个则逗号分割"
                  label="子任务ID"
                />
              </VCol>
              <VCol cols="6">
                <VAutocomplete
                  v-model="misfireStrategy"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="调度过期策略（必选项）"
                  label="调度过期策略"
                  :rules="[requiredValidator]"
                  :items="option.misfireStrategy.list"
                  item-title="title"
                  item-value="value"
                />
              </VCol>
              <VCol cols="6">
                <VAutocomplete
                  v-model="executorBlockStrategy"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="阻塞处理策略（必选项）"
                  label="阻塞处理策略"
                  :rules="[requiredValidator]"
                  :items="option.executorBlockStrategy.list"
                  item-title="title"
                  item-value="value"
                />
              </VCol>
              <VCol cols="6">
                <VTextField
                  v-model="executorTimeout"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="任务超时时间,单位秒,大于零时生效"
                  label="任务超时时间"
                />
              </VCol>
              <VCol cols="6">
                <VTextField
                  v-model="executorFailRetryCount"
                  class="lf-config-item"
                  counter
                  clearable
                  maxlength="50"
                  color="success"
                  hint="失败重试次数,大于零时生效"
                  label="失败重试次数"
                />
              </VCol>
            </VRow> 
          </VExpansionPanelText>
        </VExpansionPanel>
      </VExpansionPanels>
    </VForm>
  </div>
</template>

<script setup>
import VCron from '@/views/liteflow/cron/VCron.vue'
import { ref, watch } from 'vue'

const props = defineProps({		
  currRow: Object,
  addUrl: String,
  updateUrl: String,
  jobGroupOption: Array,
  currOption: Object,
})

const emits = defineEmits(['refreshPage', 'closeEditDialog'])

const addUrl = ref(props.addUrl)
const updateUrl = ref(props.updateUrl)
const jobGroupOption = ref(props.jobGroupOption)
const option = ref(props.currOption)

const currRow = ref(props.currRow)
const row = currRow.value
const openedPanels = ref([0, 1, 2, 3])

const isEdit = ref(!!row.id)

const id = ref(row.id || '')
const jobGroup = ref(row.jobGroup)
const jobDesc = ref(row.jobDesc || '')
const author = ref(row.author || '')
const alarmEmail = ref(row.alarmEmail || '')
const scheduleType = ref(row.scheduleType)
const scheduleConf = ref(row.scheduleConf || '')
const glueType = ref(row.glueType)
const executorHandler = ref(row.executorHandler || '')
const chainId = ref(row.chainId || '')
const executorParam = ref(row.executorParam || '')
const executorRouteStrategy = ref(row.executorRouteStrategy || 'FIRST')
const childJobId = ref(row.childJobId || '')
const misfireStrategy = ref(row.misfireStrategy || 'DO_NOTHING')
const executorBlockStrategy = ref(row.executorBlockStrategy || 'SERIAL_EXECUTION')
const executorTimeout = ref(row.executorTimeout || '')
const executorFailRetryCount = ref(row.executorFailRetryCount || '')

const getUrl = () => {
  if(isEdit.value){
    return updateUrl.value
  }
  
  return addUrl.value
}

const saveItem = () => {
  onSubmit()
}

defineExpose({
  saveItem,
})

const chainOptions = reactive([])
const executorHandlerShow = ref(false)
const scheduleConfHint = ref('')
const scheduleConfLabel = ref('')
const scheduleConfShow = ref(false)
const chainIdShow = ref(false)

watch(glueType, val => {
  changeGlueType(val)
})

onMounted(() => {
  lfChainOptionsQuery()

  const val = scheduleType.value
  if(val == 'CRON'){
    scheduleConfHint.value = 'CRON表达式（必填项）'
    scheduleConfLabel.value = 'CRON'
    scheduleConfShow.value = true
  }else if(val == 'FIX_RATE'){
    scheduleConfHint.value = '固定速度，单位秒（必填项）'
    scheduleConfLabel.value = '固定速度'
    scheduleConfShow.value = true
  }else{
    scheduleConfShow.value = false
  }

  changeGlueType(glueType.value)
})

const lfChainOptionsQuery = async (type) => {
  const res = await $ivyApi.post(API_URLS.lfChainOptions,{})
  chainOptions.push(...res.data)
}

const changeGlueType = type => {
  if(type == 'BEAN'){
    executorHandlerShow.value = true
    chainIdShow.value = false
    executorHandler.value = ''
  }else if(type == 'LITE_FLOW'){
    executorHandlerShow.value = false
    chainIdShow.value = true
    executorHandler.value = 'ivyJobHandler'
  }else{
    chainIdShow.value = false
    executorHandlerShow.value = false
    executorHandler.value = ''
  }
}

const changeScheduleType = val => {
  if(val == 'CRON'){
    scheduleConfHint.value = 'CRON表达式（必填项）'
    scheduleConfLabel.value = 'CRON'
    scheduleConfShow.value = true
  }else if(val == 'FIX_RATE'){
    scheduleConfHint.value = '固定速度，单位秒（必填项）'
    scheduleConfLabel.value = '固定速度'
    scheduleConfShow.value = true
  }else{
    scheduleConfShow.value = false
  }
  scheduleConf.value = null
}



watch(scheduleType, val => {
  changeScheduleType(val)
})



// form
const isFormValid = ref(false)
const refForm = ref()
const validResult = ref()

watch(validResult, val => {
  if(val) {
    postReq()
  }
})

const postReq = async () => {
  const res = await $ivyApi.post(getUrl(),{
    id: id.value,
    jobGroup: jobGroup.value,
    jobDesc: jobDesc.value,
    author: author.value,
    alarmEmail: alarmEmail.value,
    scheduleType: scheduleType.value,
    scheduleConf: scheduleConf.value,
    glueType: glueType.value,
    executorHandler: executorHandler.value,
    chainId: chainId.value,
    executorParam: executorParam.value,
    executorRouteStrategy: executorRouteStrategy.value,
    childJobId: childJobId.value,
    misfireStrategy: misfireStrategy.value,
    executorBlockStrategy: executorBlockStrategy.value,
    executorTimeout: executorTimeout.value,
    executorFailRetryCount: executorFailRetryCount.value,
  })

  if(res.code == 200){
    emits('closeEditDialog', val)
    emits('refreshPage', res)
    setTimeout(() => {
      nextTick(() => {
        refForm.value?.reset()
        refForm.value?.resetValidation()
      })
    }, 100)
  }
}

const onSubmit = () => {
  refForm.value?.validate().then(({ valid }) => {
    validResult.value = valid
  })
}

// cron 

const state = reactive({
  cron: "* * * * * ? *",
})

const changeCron = val => {
  if (typeof val !== "string") {return false}
  state.cron = val
  scheduleConf.value = val
}

watch(() => state.cron, (newCron, oldCron) => {
  scheduleConf.value = newCron
})
</script>

<style scoped>
.lf-config-row {
  padding-block: 10px;
  padding-inline: 4px;
}

.lf-config-row .v-col {
  padding-block-end: 3px;
}

.lf-config-item {
  padding-block-start: 8px;
}
</style>
